<template>
  <article class="page">
    <headerbar>
      积分明细
      <span v-if="isShow" @click="go('scoreMonthSummary')" class="head-btn" slot="btn"
      >统计汇总</span
      >
    </headerbar>
    <section class="frame-content-sub no-bg" style="overflow-y: hidden;">
      <supermarketHead></supermarketHead>
      <ul class="top-menu">
        <li @click="goTo(1)" :class="{ active: routeName == '1' }">
          <span>积分获取</span>
        </li>
        <li @click="goTo(2)" :class="{ active: routeName == '2' }">
              <span>积分使用</span>
        </li>

        <!--<li @click="goTo(5)"  :class="{ active: routeName == '5' }"><span>课程体验</span></li>
       <li @click="goTo(6)"  :class="{ active: routeName == '6' }"><span>课程体验</span></li>
       <li @click="goTo(7)"  :class="{ active: routeName == '7' }"><span>课程体验</span></li>-->
      </ul>
      <cube-slide
        ref="slide"
        :loop="loop"
        :initial-index="0"
        :auto-play="autoPlay"
        :show-dots="showDots"
        :options="slideOptions"
        @change="changePage"
      >
        <cube-slide-item>
          <section class="block score-bd">
            <section class="date-wraper">
              <Calendar
                v-on:choseDay="clickDay"
                v-on:changeMonth="changeDate"
              ></Calendar>
              <div style="text-align: center;line-height:36px;font-size: 14PX" @click="partOrAll(true)">
                {{calendarShowAll?"收起":"展开"}}
              </div>
              <!-- <div class="month-box">
                <i class="pre-icon" @click="changeMonth('pre')"></i>
                <h1>{{ year }}年{{ month + 1 }}月</h1>
                <i class="next-icon" @click="changeMonth('next')"></i>
              </div>
              <swiper ref="swiper" :options="swiperOption" v-if="monthList.length">
                <swiper-slide
                  class="swiper-slide"
                  v-for="(week, index) in monthList"
                  :key="index"
                >
                  <div class="week-box">
                    <div
                      class="week-item"
                      v-for="(item, index2) in week"
                      :key="index2"
                    >
                      <div class="week">{{ index2 | week }}</div>
                      <div
                        :class="[
                          'day',
                          { active: curWeekIndex - 7 * index == index2 },
                        ]"
                        @click="getList(item, index, index2)"
                      >
                        {{ item }}
                      </div>
                    </div>
                  </div>
                </swiper-slide>

                <div class="swiper-pagination" slot="pagination"></div>
              </swiper> -->
            </section>
            <cube-scroll
              ref="scroll"
              :data="todayData"
              :options="options"
              @pulling-down="onPullingDown"
            >
              <fetchData
                v-if="isLoading"
                :loading="isLoading"
                :data="todayData"
              ></fetchData>
              <div class="item" v-if="todayData" v-for="item in todayData">
                <div class="cont">
                  <div class="title">{{ item.name }}</div>
                  <div class="time">{{ getTime(item.createTime) }}</div>
                </div>
                <div class="tip">+{{ item.score }}分/次</div>
              </div>
              <div
                class="text-center no-data"
                v-if="!isLoading && todayData.length === 0"
              >
                <img src="../../../../static/images/no_data.png" alt=""/>
                <p>暂无数据</p>
              </div>
              <div class="pdv-10"></div>
            </cube-scroll>
          </section>
        </cube-slide-item>
        <cube-slide-item>
          <section class="block score-bd">
            <section class="date-wraper">
              <div class="item year-btn flex-center" @click="showTimePicker()">
                <span id="recordTimes">{{yearForConsum}}</span>
                <img class="arrow_icon" src="../../../../static/images/select_down.png">
              </div>
              <div class="right">消费<strong>{{scoreCount}}</strong>积分</div>
            </section>
            <cube-scroll
              ref="scroll"
              class="cube-scroll-wrapper1"
              :data="subDetailList"
              :options="options"
              @pulling-down="onPullingDownList"
            >
              <fetchData
                v-if="isLoading"
                :loading="isLoading"
                :data="subDetailList"
              ></fetchData>
              <div class="itemNew" v-if="subDetailList" v-for="item in subDetailList">
                <div class="img">
                  <img :src="item.mallPic" alt="">
                </div>
                <div class="cont">
                  <div class="title">{{ item.mallName }}-{{item.name}}</div>
                  <div class="time">{{ getTime(item.createTime) }}</div>
                </div>
                <div class="tip">-{{item.score}}分</div>
              </div>

              <div
                class="text-center no-data"
                v-if="!isLoading && subDetailList.length === 0"
              >
                <img src="../../../../static/images/no_data.png" alt=""/>
                <p>暂无数据</p>
              </div>
              <div class="pdv-10"></div>
            </cube-scroll>
          </section>
        </cube-slide-item>
      </cube-slide>
    </section>
  </article>
</template>

<script>
  import Calendar from "vue-calendar-component";
  import moment from "moment";
  import tools from "@/utils/tools";
  import supermarketHead from "@/components/dangjian/mall/supermarketHead.vue";
  import $ from "../../../../static/js/jquery-1.12.4.min";

  export default {
    name: "personalcenter",
    components: {supermarketHead, Calendar},
    data() {
      return {
        fn: tools,
        userInfo: {},
        isLoading: true,
        dateStr: "",
        routeName: 1,
        routeIndex: 1,
        sysFile: {},
        todayData: {},
        myIntegrals: {},
        swiperOption: {
          slidesPerView: 1,
          spaceBetween: 0,
          loopFillGroupWithBlank: true,
          //显示分页
          pagination: {
            el: ".swiper-pagination",
          },
          loop: false,
          initialSlide: 0,
          //自动轮播
          autoplay: false,
        },
        options: {
          pullUpLoad: false,
          scrollbar: false,
          pullDownRefresh: {
            threshold: 90,
            stop: 0,
            txt: " ",
          },
        },
        isShow: true,
        year: new Date().getFullYear(),
        month: new Date().getMonth(),
        yearInfoConsum: new Date().getFullYear(),
        monthInfoConsum: new Date().getMonth()+1,
        scoreCount: 0,
        monthList: [],
        curWeekIndex: 0,
        yearForConsum: '',
        _time: '',
        yearParam: '',
        monthParam: '',
        subDetailList: [],
        calendarShowAll: true, //展开状态
        loop: false,
        autoPlay: false,
        showDots: false,
        slideOptions: {
          listenScroll: true,
          probeType: 3,
          directionLockThreshold: 0,
        },
      };
    },
    filters: {
      week: function (index) {
        return ["日", "一", "二", "三", "四", "五", "六"][index];
      },
    },
    watch: {
      routeIndex(newVal) {
        this.$nextTick(() => {
          console.log('routeIndex(newVal) routeIndex(newVal) ')
          if (newVal == 2) {
            this.isShow = false
          } else {
            this.isShow = true
          }
          this.$refs.slide &&
          this.$refs.slide.slide &&
          this.$refs.slide.slide.goToPage(newVal - 1, 0, 300);
        });
      },
      routeName(newVal) {
        this.$nextTick(() => {
          if (newVal == 2) {
            this.isShow = false
            if (this.subDetailList.length == 0) {
              console.log('routeName(newVal) routeName(newVal) ')
              this.subDetail();
            }
          } else {
            this.isShow = true
          }
          var menuW = $(".top-menu").width();
          var tabLen = $(".top-menu").children().length;
          var activeDom = $(".top-menu").children(".active");
          var activeL = activeDom.offset().left;
          var activeW = activeDom.outerWidth();
          if (activeL <= 0) {
            $(".top-menu").animate({scrollLeft: 0}, 300);
          }
          if (activeL >= menuW) {
            $(".top-menu").animate({scrollLeft: activeW * (tabLen - 5)}, 300);
          }
        });
      },
    },
    created() {
      moment.lang("zh-cn");
      this.userInfo = this.$localStorage.get("userInfo");
      this.dateStr = moment().format("YYYY/MM/DD");
      this._time = new Date()
      this.yearForConsum = moment(this._time).format('YYYY年MM月')
      this.myIntegral();
      this.dayDetailList();
      this.getMonthList(new Date());
    },
    mounted() {
      this.$nextTick(() => {
        this.partOrAll(true);
      })
    },
    methods: {
      /*左右滑动事件*/
      changePage(current) {
        this.routeName = Number(current) + 1;
        console.log("滑动num", this.routeName);
      },
      onPullingDown() {
        this.todayData = [];
        console.log("onPullingDown");
        this.dayDetailList()
      },
      onPullingDownList() {
        this.subDetailList = [];
        console.log("onPullingDown");
        this.subDetail()
      },
      // 选择消费日期格式
      showTimePicker() {
        let me = this
        if (!this.datePicker) {
          let nowYear = new Date().getFullYear()
          this.datePicker = this.$createDatePicker({
            columnCount: 2,
            min: new Date(nowYear - 10, 1, 1),
            max: new Date(nowYear + 1, 1, 1),
            value: new Date(nowYear, 1, 1),
            onSelect: (selectedTime, selectedText, formatedTime) => {
              this.yearForConsum = moment(selectedTime).format('YYYY年MM月')
              console.log('---------year=', this.yearForConsum)
              this.yearInfoConsum = selectedTime.getFullYear()
              this.monthInfoConsum = selectedTime.getMonth() + 1
              this.subDetail()
            }
          })
        }
        this.datePicker.show()
        setTimeout(() => {
          this.datePicker.$updateProps({
            value: me._time
          })
        }, 100)
      },
      receive() {
        console.log()
        // this.launchOptions.pullUpLoad = true;
        // this.countNum = true;
        // this.swipeData = [];
        // this.tabIndex = 0;
        // this.pageIndex = 1;
        // this.receiveData();
      },
      clickDay(data) {
        console.log(data); //选中某天
        this.dateStr = data;
        this.dayDetailList();
      },
      changeDate(data) {
        console.log(data); //左右点击切换月份
        setTimeout(() => {
          this.partOrAll(false);
        }, 0);
      },
      // 收起展开/月份切换
      partOrAll(Boolean) {
        this.gitLineDom();
        if (Boolean) {
          //点击
          if (this.calendarShowAll) {
            //当展开时点击收起
            $(".wh_content:last")
              .children(".wh_content_item")
              .not(".current_line")
              .addClass("dis_n");
            this.calendarShowAll = false;
          } else {
            //当收起时点击展开
            $(".wh_content:last")
              .children(".wh_content_item")
              .not(".current_line")
              .removeClass("dis_n");
            this.calendarShowAll = true;
          }
        } else {
          if (this.calendarShowAll) {
            //当展开时不操作
          } else {
            //当收起时收起
            $(".wh_content:last")
              .children(".wh_content_item")
              .not(".current_line")
              .addClass("dis_n");
          }
        }
      },
      //获取收起时应该展示的那一行DOM
      gitLineDom() {
        var allItem = $(".wh_content:last").children(".wh_content_item");
        allItem.removeClass("dis_n"); //清空dis_n
        var current = $(".wh_chose_day");
        if (current.length == 0) {
          //没有点击取当前日期
          current = $(".wh_isToday");
        }
        if (current.length > 0) {
          current = current.parent();
        } else {
          //没有点击且不在本月取第一行
          current = $(".wh_content:last").children(
            ".wh_content_item:first-child"
          );
        }
        var current_top = parseInt(current.offset().top);
        console.log("current_top", current_top);
        allItem.removeClass("current_line"); //清空current_line
        allItem.each(function (i) {
          var i_iop = parseInt($(this).offset().top);
          if (i_iop == current_top) {
            $(this).addClass("current_line");
          }
        });
      },
      getList(item, index, index2) {
        this.todayData = [];
        this.isLoading = true;
        this.curWeekIndex = index * 7 + index2;
        console.log("年月日：", this.year + "-" + (this.month + 1) + "-" + item);
        this.dateStr = this.year + "-" + (this.month + 1) + "-" + item;
        this.dayDetailList();
      },
      getMonthList(cur_date) {
        this.monthList = [];
        this.swiperOption.initialSlide = 0;
        // let date = new Date();
        let monthList = [];
        // let cur_day = cur_date.getMonth() === date.getMonth() ? cur_date.getDate() : 1;
        let cur_day = cur_date.getDate();
        let cur_month = cur_date.getMonth();
        cur_date.setDate(1);
        if (cur_date.getDay() != 0) {
          // 如果1号不是星期天
          // 输出1号前面空白的星期
          for (let i = 0; i < cur_date.getDay(); i++) {
            monthList.push("");
          }
        }

        while (cur_date.getMonth() == cur_month) {
          monthList.push(cur_date.getDate());
          cur_date.setDate(cur_date.getDate() + 1);
        }

        for (let j = cur_date.getDay(); j <= 6; j++) {
          // 输出月最后一天后面空白的星期
          monthList.push("");
        }
        let num = Math.ceil(monthList.length / 7);
        for (let k = 0; k < num; k++) {
          let temp = monthList.slice(k * 7, k * 7 + 7);
          temp.forEach((item, index) => {
            if (item == cur_day) {
              this.swiperOption.initialSlide = k;
              this.curWeekIndex = k * 7 + index;
            }
          });
          // 清除一周内全是''的星期
          let isNull = temp.every((item) => {
            return item === "";
          });
          if (!isNull) {
            this.monthList.push(temp);
          }
        }
        // console.log(this.monthList, this.swiperOption.initialSlide);
      },
      changeMonth(type) {
        if (type === "pre") {
          this.year = this.month - 1 === -1 ? this.year - 1 : this.year;
          this.month = this.month - 1 === -1 ? 11 : this.month - 1;
        } else {
          this.year = this.month + 1 === 12 ? this.year + 1 : this.year;
          this.month = this.month + 1 === 12 ? 0 : this.month + 1;
        }
        console.log("年月：", this.year + "-" + (this.month + 1));
        this.getMonthList(new Date(this.year, this.month, 1));
      },
      percent(data) {
        let dayMaxScore = data.dayMaxScore;
        if (data.dayMaxScore === 0) {
          dayMaxScore = data.dayMaxScore + 10;
        }
        return (data.hasScore / dayMaxScore) * 100 + "%";
      },
      //点击tab
      goTo(num) {
        this.routeName = num;
        this.routeIndex = num;
      },
      completeText(data) {
      },
      go(path) {
        this.$router.push({path: path});
      },
      getTimeDay(createTime) {
        if (!createTime) {
          return "";
        }
        return moment(createTime).format("MM月DD日");
      },
      myIntegral() {
        let data = {
          userId: this.userInfo.id,
        };
        this.fetchService.myIntegral(data.userId).then((res) => {
          if (res.code !== 0) {
            return tools.tip(res.message);
          }
          this.myIntegrals = res.data;
        });
      },
      dayDetailList() {
        this.todayData = [];
        this.isLoading = true;
        let dateStr = this.dateStr.split("/");
        let data = {
          userId: this.userInfo.id,
          day:
            Number(dateStr[2]) > 9
              ? Number(dateStr[2]) + ""
              : "0" + Number(dateStr[2]),
          month:
            Number(dateStr[1]) > 9
              ? Number(dateStr[1]) + ""
              : "0" + Number(dateStr[1]),
          year: "" + dateStr[0],
        };
        this.fetchService.detailList(data).then((res) => {
          this.isLoading = false;
          if (res.code !== 0) {
            return tools.tip(res.message);
          }
          this.todayData = res.data;
          console.log(this.todayData);
          setTimeout(() => {
            this.$refs.scroll.forceUpdate &&
            this.$refs.scroll.forceUpdate(true, false);
          }, 100);
        });
      },
      subDetail() {
        let data = {
          "businessId": "",
          "day": "",
          "mallId": "",
          "month": Number(this.monthInfoConsum) > 9
            ? Number(this.monthInfoConsum) + ""
            : "0" + Number(this.monthInfoConsum),
          "productId": "",
          "userId": this.userInfo.id,
          "year": this.yearInfoConsum
        }
        this.isLoading = true
        this.subDetailList = []
        this.fetchService.subDetail(data).then((res) => {
          this.isLoading = false;
          if (res.code !== 0) {
            return tools.tip(res.message);
          }
          this.subDetailList = res.data
          this.scoreCount = 0
          this.subDetailList.forEach(item => {
            this.scoreCount += item.score
          })
          console.log('res.datares.data', res.data);
        });
      },
      getTime(createTime) {
        return moment(createTime).format("YYYY年MM月DD日 HH:mm:ss");
      },
    },
  };
</script>

<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";

  .page {
    .head-btn {
      font-size: 12PX;
      border: 0;
    }
  }

  .mine-page {
    /*background: url("../../../../static/images/dangjian/mine/bg-mine-hd.png") $bg-color no-repeat center #{pxToRem($head-height)};
      background-size: 100% auto;*/
    padding: 0;

    .header {
      justify-content: space-between;
      margin-bottom: pxToRem(0px);
      position: relative;
    }
  }

  p {
    font-size: 14PX;
  }

  .score-hd {
    height: 242px;
    text-align: center;
    background: url("../../../../static/images/dangjian/mine/bg-mine-hd.png") $theme-color no-repeat center;
    background-size: 100% auto;
    display: flex;
    justify-content: space-around;
    align-items: center;

    .score-head {
      width: 118px;
      height: 118px;
      border-radius: 50%;
      overflow: hidden;
      border: 4px solid #ea7676;

      img {
        height: 100%;
        width: 100%;
      }
    }

    .score-text {
      margin-right: 50px;
      text-align: left;

      .score-tip {
        .score-tip-text {
          vertical-align: super;
          color: #ffffff;
        }
      }
    }

    .score-play {
      width: 171px;
      height: 46px;
      line-height: 46px;
      background: #e20001;
      border: 1px solid #ffffff;
      border-radius: 10px;
      color: #ffffff;
      opacity: 0;
    }

    .score {
      font-size: 56PX;
      line-height: 1.2em;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      margin-right: 10px;
    }

    .tip {
      font-size: 12PX;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
    }
  }

  .score-bd {
    padding: 10px 30px;

    .date-wraper {
      /*background: #fff;
        border-radius: 20px;
        box-shadow:0px 2px 16px 0px rgba(32,21,18,0.41);
        padding: 0 34px;*/
      border-bottom: 1px solid #e5e5e5;
      box-sizing: border-box;

      .year-btn {
        color: #333;
        border: none;
        border-radius: 0.66667rem;
        padding: 0.05333rem 0.24rem;
        font-size: 16PX;
        width: 35%;
        height: 38PX;
        border-radius: unset;
        background: none;

        .arrow_icon {
          width: 0.30667rem !important;
          margin-left: 0.10667rem;
        }
      }

      .right {
        float: left;
        font-size: 15PX;
        position: absolute;
        right: 3%;
        top: 2%;
        height: 38PX;
        font-weight: bold;

        > strong {
          color: #e20002;
          font-size: 20PX;
          margin: 0 8PX;
        }
      }

      .month-box {
        display: flex;
        height: 95px;
        justify-content: space-around;
        align-items: center;
        border-bottom: 1px solid #e5e5e5;

        i {
          display: inline-block;
          width: pxToRem(21px);
          height: pxToRem(35px);

          &.pre-icon {
            background: url("../../../../static/images/dangjian/mall/arrow-left.png") no-repeat center;
            background-size: auto 100%;
          }

          &.next-icon {
            background: url("../../../../static/images/dangjian/mall/arrow-right.png") no-repeat center;
            background-size: auto 100%;
          }
        }
      }

      .week-box {
        padding: 20px 0 60px;
        display: flex;
        justify-content: space-between;

        .week-item {
          .week {
            text-align: center;
            font-size: 16PX;
            color: #999999;
            margin-bottom: 34px;
          }

          .day {
            font-size: 16PX;
            color: #333333;
            margin-bottom: 20px;
            width: 62px;
            height: 62px;
            text-align: center;
            line-height: 62px;
            border-radius: 50%;
            background: #ffffff;

            &.active {
              background: #ec860d;
              color: #ffffff;
            }
          }
        }
      }
    }

    .item {
      display:flex;
      justify-content:space-between;
      align-items:center;
      padding:37px 0;
      border-bottom:1px solid $border-color;
      &:last-child {
        border:none;
      }
      .cont {
        width: 75%;
        .title {
          font-size: 16PX;
          font-weight: 400;
          color: rgba(51, 51, 51, 1);
        }

        .time {
          font-size: $tipFontSize;
          font-weight: 400;
          color: rgba(153, 153, 153, 1);
        }
      }
      .tip {
        font-size: 16PX;
        color: #E20002;
      }
    }

    .itemNew {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 37px 0;
      border-bottom: 1px solid $border-color;

      &:last-child {
        border: none;
      }

      .cont {
        width: 60%;
        text-align: left;
        .title {
          font-size: 15PX;
          font-weight: bold;
          text-align: left ;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          display: -webkit-box;
          float: left;
          /*-webkit-box-pack: center;*/
          /*-ms-flex-pack: center;*/
          /*justify-content: center;*/
          /*-ms-flex-direction: column;*/
          /*flex-direction: column;*/
          /*margin-left: 0px;*/
        }

        .time {
          font-size: $tipFontSize;
          font-weight: 400;
          color: rgba(153, 153, 153, 1);
          float: left;
        }
      }

      .tip {
        font-size: 16PX;
        color: #e20002;
        width: 20%;
        text-align: right;
      }

      .img {
        margin-right: 0.3rem;
        /*float: left;*/
        position: relative;
        overflow: hidden;
        width: 1.6rem;
        height: 1.6rem;
        background: none;
        border-radius: 50%;
        -ms-flex-negative: 0;
        flex-shrink: 0;
        background: #f6f6f6;

        > img {
          position: relative;
          overflow: hidden;
          width: 1.6rem;
          border-radius: 50%;
          -ms-flex-negative: 0;
          flex-shrink: 0;
        }

        .bdt {
          background: #ffb800;
          width: 100%;
          height: 100%;
          text-align: center;

          > span {
            color: #ffffff;
            font-size: 1.5rem;
            text-align: center;
            line-height: 12vh;
          }
        }
      }
    }
  }

  .mine-page > > > .swiper-pagination-bullet-active {
    background: #ec850c;
  }

  .message {
    .head-btn-text {
      position: absolute;
      top: 50%;
      right: 0.4rem;
      -webkit-transform: translate3d(0, -50%, 0);
      transform: translate3d(0, -50%, 0);
      white-space: nowrap;
      font-size: 12PX;
      border-radius: 0.13333rem;
      line-height: 0.58667rem;
      font-weight: 400;
      text-align: center;
      color: #fff;
    }
  }

  .top-menu {
    display: flex;
    justify-content: flex-start;
    padding: 0 pxToRem(0px);
    background: rgba(255, 255, 255, 1);
    border: 1px solid #e5e5e5;
    width: 100vw;
    overflow-x: scroll;
    -ms-overflow-style: none;
    scrollbar-width: none;

    &::-webkit-scrollbar,
    &::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }

    li {
      font-size: 14PX;
      font-weight: 400;
      width: 20%;
      flex-shrink: 0;
      text-align: center;
      color: rgba(0, 0, 0, 1);
      padding: pxToRem(10px) 0;
      line-height: pxToRem(60px);
      margin: auto;

      &.active {
        font-size: 16PX;
        border-bottom: 2px solid $theme-color;
        font-weight: bold;
        color: rgba(226, 0, 1, 1);

        span {
          font-size: 16PX;
        }
      }

      span {
        font-size: 14PX;
        font-weight: bold;
      }
    }
  }
  /*height: calc(100vh - #{pxToRem(60px)} - #{pxToRem(50px)} - #{pxToRem(170px)} - calc(100vw * 9 / 16));*/
  .cube-scroll-wrapper {
    height: 11.5rem;
  }
  .cube-scroll-wrapper1 {
    height: 15rem;
  }
  .cube-scroll-list-wrapper {
    overflow: hidden;
  }
</style>
